<template>
  <div :class="$style.upload">
    <Button type="primary" :disabled="$attrs.disabled === true" @click="visible=true">{{ text }}<i v-if="showFileNum" :class="$style.fileNum">({{ showFileList.length }}个)</i></Button>
    <!-- 显示文件 -->
    <!-- <div :class="$style.fileList">
      <Button type="primary" :disabled="$attrs.disabled === true" @click="visible=true">{{ text }}</Button>
      <ul>
        <li v-for="(file,i) in showFileList" :key="i" @click="previewHandle(file, showFileList)">{{ file.fileName || file.name }}</li>
      </ul>
    </div> -->
    <el-dialog
      :close-on-click-modal="false"
      :show-close="false"
      :destroy-on-close="destroy"
      :visible.sync="visible"
      :title="title"
      :append-to-body="true"
      @close="resetHandle"
    >
      <div :class="$style.bodyWrap">
        <Upload ref="upload" :exist-file-list="existFileList" :on-preview="previewHandle" :auto-upload="autoUpload" v-bind="$attrs" @currentUpload="currentUploadHandle" @cancel="cancelUploadHandle" />
        <Button v-if="downTempUrl!==''" type="primary" @click="downTempHandle">{{ downTempText }}</Button>
      </div>
      <div slot="footer">
        <Button @click="cancelHandle">取消</Button>
        <Button type="primary" @click="confirmHandle">{{ confirmButtonText }}</Button>
      </div>
    </el-dialog>
    <PreviewImage v-model="previewShow" :prefix="prefix" :image-list="imageList" />
  </div>
</template>
<script>
import Upload from '@/components/Upload'
import Button from '@/components/Button'
import PreviewImage from '@/components/PreviewImage'
import { deepCopy, downFileByStream } from '@/utils'
import request from '@/utils/request'
export default {
  name: 'DialogUpload',
  components: {
    Upload,
    Button,
    PreviewImage
  },
  inheritAttrs: false,
  props: {
    // 已上传的文件
    existFileList: {
      type: Array,
      default: () => []
    },
    title: {
      type: [Number, String],
      default: '上传附件'
    },
    text: {
      type: [Number, String],
      default: '上传附件'
    },
    confirmButtonText: {
      type: [Number, String],
      default: '确定'
    },
    destroy: {
      type: Boolean,
      default: true
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    clickDown: {
      type: Boolean,
      default: true
    },
    prefix: {
      type: String,
      default: '/img/'
    },
    showFileNum: { // 是否显示文件个数
      type: Boolean,
      default: true
    },
    // 下载模板
    downTempText: {
      type: String,
      default: '下载模板'
    },
    // 下载模板url
    downTempUrl: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      imageList: [],
      previewShow: false,
      currentUploadFileList: [], // 本次上传文件列表
      fileList: [] // 显示文件列表
    }
  },
  computed: {
    showFileList() {
      if (this.fileList.length > 0) {
        return this.fileList
      }
      return [...this.existFileList, ...this.currentUploadFileList]
    }
  },
  methods: {
    // 是图片
    isImage(file) {
      // FIXME:根据实际情况修改
      return /(png$)|(jpg$)|(gif$)|(jpeg$)|(bmp$)/.test(file.name || file.url)
    },
    // 不是图片直接查看
    openFile(file) {
      const a = document.createElement('a')
      // FIXME: 根据实际情况修改
      let url = file.url
      console.log('文件', url)
      const objExp = new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/)
      if (!objExp.test(url)) {
        if (!/^\/img/.test(url)) {
          url = this.prefix + url
        }
      }
      a.href = url
      a.download = file.name
      a.target = '_bank'
      // document.body.append(a)
      a.click()
    },
    // 预览
    previewHandle(file, fileList) {
      if (this.isImage(file)) {
        this.imageList = fileList.filter(e => {
          return this.isImage(e)
        })
        this.previewShow = true
      } else {
        if (this.clickDown && file.status !== 'ready') {
          this.openFile(file)
        }
      }
    },
    resetHandle() {
      this.imageList = []
      this.previewShow = false
    },
    // 全部清空
    cancelAllHandle() {
      const upload = this.$refs.upload
      upload.clearFiles()
      const fileList = deepCopy(upload.fileList)
      while (fileList.length > 0) {
        const file = fileList.splice(0, 1)
        this.$refs.upload.onRemoveHandle(file[0], fileList)
      }
      this.visible = false
    },
    // 取消本次上传
    cancelHandle() {
      const fileList = deepCopy(this.$refs.upload.fileList)
      const currentUploadFileList = this.currentUploadFileList
      for (const f of currentUploadFileList) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === f.uid) {
            fileList.splice(i, 1)
            continue
          }
        }
      }
      while (currentUploadFileList.length > 0) {
        const file = currentUploadFileList.splice(0, 1)
        this.$refs.upload.onRemoveHandle(file[0], fileList)
      }
      this.visible = false
    },
    confirmHandle() {
      this.$emit('confirm', this.currentUploadFileList)
      this.currentUploadFileList = []
      this.visible = false
    },
    // 记录本次上传
    currentUploadHandle(file, fileList) {
      this.currentUploadFileList.push(file)
      this.fileList = fileList
    },
    // 选择后取消
    cancelUploadHandle(file, fileList) {
      this.fileList = fileList
    },
    // 下载模板
    downTempHandle() {
      return request({
        method: 'GET',
        url: this.downTempUrl,
        responseType: 'blob'
      }).then(res => {
        downFileByStream(res.data, this.fileName)
      })
    }
  }
}
</script>
<style lang="scss" module>
.upload{
    display: inline-block;
    & .fileNum{
      color: red;
      font-style: normal;
      padding: 0 4px;
    }
    & .fileList{
      width: 100%;
      text-align: right;
      &>ul{
        text-align: left;
        width: 100%;
        padding: 10px 0 0 0;
        margin: 0;
        list-style: none;
        &>li{
          display: inline-block;
          margin-bottom: 5px;
          padding: 4px;
          border-radius: 4px;
          cursor: pointer;
          &:hover{
            color: #16BC83;
          }
        }
        &>li + li{
          margin-left: 10px;
        }
      }
    }
}
.bodyWrap{
  display: flex;
  align-items: flex-start;
  &>*:not(:first-child){
    margin-left: 10px;
  }
}
</style>
